package top.hhydra.mimall.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.hhydra.mimall.enums.ResponseEnum;
import top.hhydra.mimall.vo.ResponseVo;

import java.util.Objects;

/**
 * @Description
 * @auther SaiyeEmon
 * @create 2020-02-11 0:59
 */
@ControllerAdvice
@Slf4j
public class RuntimeExceptionHandler {

    @ExceptionHandler(UserLoginException.class)
    @ResponseBody
    public ResponseVo<String> loginExceptionHandler() {
        return ResponseVo.error(ResponseEnum.LOGIN_ERROR);
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseVo<String> runtimeExceptionHandler(RuntimeException e) {
        log.error("出现异常:", e);
        log.error("出现异常:{}", e.getMessage());
        return ResponseVo.error(ResponseEnum.ERROR, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseVo<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Objects.requireNonNull(bindingResult.getFieldError());
        return ResponseVo.error(ResponseEnum.ERROR,
                bindingResult.getFieldError().getField()
                        + " " + bindingResult.getFieldError().getDefaultMessage());
    }

}
